<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

const animationDuration = 2000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    unit: {
      type: String,
      default: '个'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: true
    },
    title: {
      type: String,
      required: true
    }
  },
  watch: {
    chartData:{
      handler(val) {
        this.chart.clear()
        this.setOptions(val)
      },
      deep: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({xAxisData, yAxisData, stack=''}) {
      let series = [{
        type: 'bar',
        stack: 'vistors',
        barWidth: '60%',
        data: yAxisData,
        animationDuration
      }]
      if(stack) {
        series = yAxisData.map((item, index) => {
          return {
            name: item.name,
            type: 'bar',
            stack: 'vistors',
            data: item.data,
            animationDuration
          }
        })
      }
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: '5%',
          left: '5%',
          right: '10%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: [{
          type: 'value',
          name: '(' +this.unit+ ')',
          axisTick: {
            alignWithLabel: true
          },

        }],
        yAxis: [{
          type: 'category',
          axisTick: {
            show: false
          },
          data: xAxisData,
          axisLabel: {
            formatter: function(value) {
              // 每5个字符换行
              return value.replace(/(.{6})/g, '$1\n')
            }
          },
          inverse:true,
        }],
        series
      })
    }
  }
}
</script>
